import type { App } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import remainingRouter from './modules/remaining'
import { MessageBoxData } from 'element-plus'

// 创建路由实例
const router = createRouter({
  // 路由模式使用 hash，使用 history 的话，Apache 或 NGINX 等静态页面服务器需要配置伪静态规则，不然刷新会 404
  history: createWebHashHistory(import.meta.env.VITE_BASE_PATH),
  strict: true,
  routes: remainingRouter as RouteRecordRaw[],
  scrollBehavior: () => ({ left: 0, top: 0 })
})
router.onError((error) => {
  if (
    import.meta.env.PROD &&
    error.message.startsWith('Failed to fetch dynamically imported module')
  ) {
    const { confirm } = useMessage()
    confirm('网页内容已经更新，请点击确认刷新页面。', '更新提示').then((res: MessageBoxData) => {
      if (res.action == 'confirm') {
        location.reload()
      }
    })
  }
})

export const resetRouter = (): void => {
  const resetWhiteNameList = ['Redirect', 'Login', 'NoFound', 'Home']
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name && !resetWhiteNameList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

export const setupRouter = (app: App<Element>) => {
  app.use(router)
}

export default router
